package com.ufo.threads.limits;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Semaphore;

public class SemaphoreUse {
    static long countL=0;//多线程不安全的计数器
    static Semaphore s=new Semaphore(10);//限制并发数，可以看作是可多次分享的锁
    //信号可以用于限流
    public static void main(String[] args){
        parkingLot();
    }

    public static void parkingLot(){
        Runnable r=new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("===="+Thread.currentThread().getName()+"来到停车场");
                    if(s.availablePermits()==0){
                        System.out.println("车位不足，请耐心等待");
                    }
                    s.acquire();//获取令牌尝试进入停车场
//                    boolean b = s.tryAcquire();// 也可以tryAcquire不阻塞，放弃停车
//                    if(!b){
//                        System.out.println(Thread.currentThread().getName()+"放弃等待");
//                        return;
//                    }
                    System.out.println(Thread.currentThread().getName()+"成功进入停车场");
                    Thread.sleep(new Random().nextInt(2000));//模拟车辆在停车场停留的时间
                    System.out.println(Thread.currentThread().getName()+"驶出停车场");
                    s.release();//释放令牌，腾出停车场车位
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        for(int i=0;i<100;i++){//100辆车，只有10个停车位
            Thread t=new Thread(r);
            t.start();
        }
    }

    public static void ezUse(){
        Thread[] allThreads = new Thread[100];
        for (int index = 0; index < allThreads.length; index++) {
            allThreads[index] = new Thread(() -> {
                for (int i = 0; i < 100; i++) {
                    try {
                        s.acquire();//permits+1
                        System.out.println(s.getQueueLength());
                        countL++;
                        System.out.println(Thread.currentThread() + ":count:" + countL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        s.release();//permits-1
                    }

                }
            });
        }
        for (Thread t : allThreads) t.start();
        for (Thread t : allThreads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
